/**
 * Created by caosh on 2018/1/22 0022.
 */
// 购物车-混合
var CartMixin = {
    data: {
        numObj: {}, // 用于记录所有购物车里的数据
        cartTotal: 0, // 总金额
        cartNum: 0, // 总数量
        cartProducts: [] // 购物车数据容器
    },
    computed: {
        cartNumFilter: function () {
            if (this.cartNum == 0) {
                return '';
            } else if (this.cartNum > 99) {
                return '99+';
            } else {
                return this.cartNum;
            }
        }
    },
    methods: {
        changeNumObj: function (p) {
            this.numObj[p.id+'-'+p.nId] = p.num;
        },
        // 商品数量增加
        cartPlus: function (p) {
            p.num++;
            this.changeNumObj(p);
        },
        // 商品数量减少
        cartReduce: function (p) {
            /*p.num--;
            if (p.num <= 0) {
                this.removeProduct(p);
            }*/
            if (p.num > 0) {
                p.num--;
                this.changeNumObj(p);
            }
            this.triggerRemoveProduct(p.num, p);
        },
        triggerRemoveProduct: function (n, p) {
            if (n == 0) {
                this.removeProduct(p);
            }
        },
        // 移除购物车中指定商品
        removeProduct: function (p) {
            this.cartProducts.splice(this.cartProducts.indexOf(p), 1);
        },
        // 获得购物车数据
        getCartProducts: function () {
            this.cartProducts = store.get('products') || [];
        },
        // 获得购物车中指定数据
        getCartProduct: function (p, n) {
            return this.cartProducts.filter((o, i, arr) => {
                    return p.id == o.id && o.nId == n.id;
                }) || [];
        },
        // 获得购物车商品数量
        getCartProductsNum: function () {
            this.cartNum = 0;
            this.cartProducts.forEach((o, i, arr) => {
                this.cartNum += o.num;
            });
        },
        // 获取购物车商品总金额
        getCartProductsTotal: function () {
            this.cartTotal = 0;
            this.cartProducts.forEach((o, i, arr) => {
                this.cartTotal += (o.num * o.unitPrice);
            });
        },
        // 本地缓存购物车数据
        cacheCartProducts: function () {
            store.set('products', this.cartProducts);
        },
        // 从缓存池取出缓存对象
        getProductFromPool: function (p, n) {
            var arr = this.getCartProduct(p, n);
            if (arr.length <= 0) {
                return this.deepCopy(p);
            }

            return arr[0];
        },
        // 编辑商品-选中商品
        selectProduct: function (product) {
            if (!product.hasOwnProperty('isSelected')) {
                Vue.set( product, 'isSelected', false );
            }

            if (product.isSelected) {
                product.isSelected = false;
            } else {
                product.isSelected = true;
            }
        },
        // 拷贝订单对象
        deepCopy: function (p) {
            var result = {};

            for (var key in p) {
                result[key] = typeof p[key] === 'object' ? this.deepCopy(p[key]) : p[key];
            }

            return result;
        },
        // 去支付
        submitOrder: function () {
            store.set('order', {products: this.cartProducts, total: this.cartTotal});
            window.location.href = '../cart/order.html';
        }
    },
    watch: {
        cartProducts: {
            handler(newValue, oldValue) {
                this.getCartProductsNum();
                this.getCartProductsTotal();
                this.cacheCartProducts();
            },
            deep: true
        }
    }
}

// 产品-混合
var ProductMixin = {
    data: {
        allProducts: [], // 全部商品
        oftenBuyList: [], // 常购清单
        recommends: [], // 推荐
        searchResults: [], // 查询结果
        productCategories: ['调理美食', '速食快餐', '冷冻肉类', '冷冻海鲜', '火锅丸子', '休闲小吃', '速冻果蔬', '精选套餐'],
        saleCategories: ['促销', '爆品', '高利润', '四个字的'],
        scs: {
            '调理美食': ['促销', '爆品', '高利润', '四个字的'],
            '速食快餐': ['促销',  '四个字的'],
            '冷冻肉类': ['四个字的'],
            '冷冻海鲜': ['促销'],
            '火锅丸子': ['爆品'],
            '休闲小吃': ['高利润'],
            '速冻果蔬': ['爆品', '四个字的'],
            '精选套餐': ['促销', '高利润']
        }
    },
    methods: {
        // 模拟产品数据(100条)
        imitateProducts: function () {
            var names = [
                {n: '乇乇肉', pc: '冷冻肉类', sc: ['四个字的']},
                {n: '[镇游民]大鸡排', pc: '速食快餐', sc: ['四个字的']},
                {n: '高利润豆瓣酱', pc: '调理美食', sc: ['高利润']},
                {n: '撒尿牛丸', pc: '火锅丸子', sc: ['爆品']},
                {n: '甜面酱', pc: '调理美食', sc: ['促销', '爆品', '高利润', '四个字的']},
                {n: '促销甜面酱', pc: '调理美食', sc: ['促销']},
                {n: '豆瓣酱', pc: '调理美食', sc: ['爆品']},
                {n: '老干妈', pc: '调理美食', sc: ['爆品']},
                {n: '撒尿牛丸', pc: '火锅丸子', sc: ['高利润']},
                {n: '河虾', pc: '冷冻海鲜', sc: ['促销']},
                {n: '甜筒', pc: '休闲小吃', sc: ['高利润']},
                {n: '大白菜', pc: '速冻果蔬', sc: ['爆品', '高利润']},
                {n: '全家桶套餐', pc: '精选套餐', sc: ['促销', '高利润']},
                {n: '[隆泰]一级沙拉', pc: '速食快餐', sc: ['促销']}
            ], arr = [true, false];

            for (var i = 1; i <= 90; i++) {
                // 随机商品 和 是否常购
                var index = i%9,
                    isOftenBuy = arr[Math.floor(Math.random() * arr.length)],
                    isRecommend = arr[Math.floor(Math.random() * arr.length)],
                    name = names[index],
                    p = {
                        id: i,
                        img: '../../../public/images/product.png',
                        name: name.n,
                        categorie: name.pc,
                        saleCategorie: name.sc,
                        norm: '1kg/包x10包/件',
                        basePrice: '138.0',
                        priceList: [{
                            money: '135.0',
                            num: '1-2'
                        }, {
                            money: '133.0',
                            num: '3-5'
                        }, {
                            money: '130.0',
                            num: '≥5'
                        }],
                        unit: '包',
                        moneyUnit: '元',
                        normList: [{id: 2, price: '320', unit: '件'}, {id: 1, price: '130', unit: '包'}],
                        isOftenBuy: isOftenBuy,
                        isRecommend: isRecommend, // 是否推荐
                        showNorm: false,
                        buttonSelect: false,
                        touch: false
                    };

                this.allProducts.push(p);
            }
        },
        // 获得常购清单
        getOftenBuyList: function () {
            this.oftenBuyList = this.allProducts.filter((p, i, arr) => {
                return p.isOftenBuy;
            });
        },
        removeOftenBuy: function (p) {
            p.isOftenBuy = true;
            this.oftenBuyList.splice(this.oftenBuyList.indexOf(p), 1);
            this.allProducts[this.allProducts.indexOf(p)] = p;
        },
        // 获得推荐商品
        getRecommends: function () {
            this.recommends = this.allProducts.filter((p, i, arr) => {
                return p.isRecommend;
            });
        },
        // 通过名称查询
        getProductsByName: function (name) {
            this.searchResults = this.allProducts.filter((p, i, arr) => {
                return p.name.indexOf(name) != -1;
            });
        },
        // 通过分类查询
        getProductsByCategorie: function (products, categorie) {
            this.searchResults = products.filter((p, i, arr) => {
                return p.categorie == categorie;
            });
        },
        // 通过sale-category查询
        getProductsBySaleCategorie: function (saleCategorie) {
            this.searchResults = this.searchResults.filter((p, i, arr) => {
                return p.saleCategorie.indexOf(saleCategorie)!=-1;
            });
        },
        getProductCategories: function (i, n, c) {
            var l = c-n,
                j = (i==0?0:i*(n+l)-l),
                arr = [],
                k=0;

            for (; j<(i+1)*n+i; j++) {
                if (j >= this.productCategories.length) {
                    break;
                }
                arr[k++] = this.productCategories[j];
            }

            return arr;
        },
        showDetails: function (p) {
            store.set('details', p);
        },
        closeDetails: function () {
            store.remove('details');
        }
    },
    mounted: function () {
        this.imitateProducts();
    }
}

var SystemMixin = {
    data: {
        consumerHotline: ''
    },
    directives: {
        focus: {
            inserted: function (el) {
                el.focus();
                $(el).select();
            }
        },
        click: {
            inserted: function (el) {
                el.addEventListener('click', function () {
                    $('#cart-product-num').focus();
                });
                $(el).trigger('click');
            }
        }
    },
    methods: {
        getDefaultStore: function () {
            var defaultStore = store.get('currentStore') || store.get('defaultStore') || null;
            if (defaultStore == null) {
                var user = this.getUser();
                if (user == null) {
                    // 未登录 跳转到登录页面
                    window.location.href = '../login.html';
                } else {
                    // 后台获取默认门店
                    /*
                     $.ajax({
                        type: 'POST',
                        url: url,
                        data: user,
                        async: false,
                        dataType: 'json',
                        success: function(result){
                            defaultStore = result;
                        }
                     });
                     */
                    var result = {
                        name: '门店名',
                        region: '广东省广州市海珠区',
                        location: '景泰街道到到 100000号',
                        phone: '13745678910',
                        personName: '路人甲',
                        business: '',
                        isDefault: true
                    };
                    defaultStore = result;
                    return defaultStore;
                }
            } else {
                return defaultStore;
            }
        },
        getUser: function () {
            return store.get('user') || null;
        },
        getConsumerHotline: function () {
            var _this = this;
            /**
             $.get(url, function(result){
                _this.consumerHotline = result.consumerHotline;
             }, 'json');
             */
            var result = {consumerHotline: '13145678910'};
            _this.consumerHotline = result.consumerHotline;
        },
        goBack: function () {
            window.history.back(-1);
        },
        showToast: function (msg, flag, duration, bgcolor) {
            var iconClass = 'iconfont ',
                className= 'bsz-toast ';
            if (flag == 'success') {
                iconClass += 'icon-success iconfont-g';
            } else if (flag == 'error') {
                iconClass += 'icon-cuowuguanbiquxiao-xianxingyuankuang iconfont-r';
            }

            if (bgcolor == 'black') {
                className += 'bsz-toast-black';
            }

            this.$toast({
                message: msg,
                iconClass: iconClass,
                className: className,
                duration: duration
            });
        }
    }
}